<template>
  <div class="dropdown-menuMax">
    <div class="dropdown-menu">
      <div
        class="custom-select"
        @click.stop="
          drawerVisible = true;
          isShow = !isShow;
          // isShow ? '' : fetchData();
        "
      >
        {{ `${dateRangeStart} - ${dateRangeEnd}` }}
      </div>
      <!-- <el-date-picker
          v-model="daterange"
          style="width: 260px"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :size="size"
        /> -->
      <button @click="isShow = false" v-if="isShow" class="button">确定</button>
    </div>
    <div v-if="isShow" class="scustom-select-content">
      <div class="selectShow time">
        <span class="span">{{ "时间范围:" }}</span>
        <div class="inputtiem">
          <!-- <el-date-picker
              v-model="daterange"
              style="width: 260px"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :size="size"
            /> -->
          <!-- <el-date-picker
            v-model="date"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          /> -->
          <input
            type="datetime-local"
            v-model="dateRangeStart"
            placeholder="开始时间"
            @click="showDateTimePicker($event)"
          />
          <input
            type="datetime-local"
            v-model="dateRangeEnd"
            placeholder="结束时间"
            :min="dateRangeStart"
            @click="showDateTimePicker($event)"
          />
        </div>
      </div>
      <div
        class="selectShow"
        v-if="props.type == 'construction' ? false : true"
      >
        <span class="span">{{ "是否亡人事故:" }}</span>
        <div class="custom-select" @click="isFatalChange = !isFatalChange">
          {{ isFatalLabel || "是否亡人事故" }}
        </div>
        <div class="custom-options" v-if="isFatalChange">
          <div
            v-for="item in fatalOptions"
            :key="item.value"
            class="custom-option"
            @click.stop="selectFatalOption(item)"
          >
            {{ item.label }}
          </div>
        </div>
      </div>
      <div
        class="selectShow"
        v-if="props.type == 'construction' ? false : true"
      >
        <span class="span">{{ "是否受伤:" }}</span>
        <div class="custom-select" @click="isInjuredChange = !isInjuredChange">
          {{ isInjuredLabel || "是否伤人事故" }}
        </div>
        <div class="custom-options" v-if="isInjuredChange">
          <div
            v-for="item in injuredOptions"
            :key="item.value"
            class="custom-option"
            @click.stop="selectInjuredOption(item)"
          >
            {{ item.label }}
          </div>
        </div>
      </div>
      <div
        class="selectShow"
        v-if="props.type == 'construction' ? false : true"
      >
        <span class="span">{{ "有无隔离设施:" }}</span>
        <div class="custom-select" @click="isGeLiSheshi = !isGeLiSheshi">
          {{ hasIsolationLabel || "有无隔离设施" }}
        </div>
        <div class="custom-options" v-if="isGeLiSheshi">
          <div
            v-for="item in isolationOptions"
            :key="item.value"
            class="custom-option"
            @click.stop="selectIsolationOption(item)"
          >
            {{ item.label }}
          </div>
        </div>
      </div>
      <div
        class="selectShow"
        v-if="props.type == 'construction' ? false : true"
      >
        <span class="span">{{ "事故原因:" }}</span>
        <div
          class="custom-select"
          @click="isGeneralOptions = !isGeneralOptions"
        >
          {{ selectedCause || "事故原因" }}
        </div>
        <div class="custom-options" v-if="isGeneralOptions">
          <div
            v-for="cause in accidentCauses"
            :key="cause.id"
            class="custom-option"
            @click.stop="selectCause(cause)"
          >
            {{ cause.value }}
          </div>
        </div>
      </div>
      <div
        class="selectShow"
        v-if="props.type == 'construction' ? false : true"
      >
        <span class="span">{{ "事故形式:" }}</span>
        <div
          class="custom-select"
          @click="isGeneralOptions1 = !isGeneralOptions1"
        >
          {{ selectedForm || "事故形式" }}
        </div>
        <div class="custom-options" v-if="isGeneralOptions1">
          <div
            v-for="pattern in accidentPatterns"
            :key="pattern.id"
            class="custom-option"
            @click.stop="selectForm(pattern)"
          >
            {{ pattern.value }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
  <script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import {
  GetAccident,
  GetAccidentPattern,
  GetAccidentCause,
} from "../../service/api/map";
interface Props {
  type: string;
  isActive: boolean;
}
const props = defineProps<Props>();
// const dateRange = getDateRange();
// const getDateRange = () => {
//   if (date.value && date.value[0] && date.value[1]) {
//     return {
//       startTime: dayjs(date.value[0]).format("YYYY-MM-DD") + " 00:00:00",
//       endTime: dayjs(date.value[1]).format("YYYY-MM-DD") + " 23:59:59",
//     };
//   }
//   return {
//     startTime: dayjs().subtract(30, "day").format("YYYY-MM-DD") + " 00:00:00",
//     endTime: dayjs().format("YYYY-MM-DD") + " 23:59:59",
//   };
// };
// 获取当前日期的 00:00:00 和 23:59:59
const now = new Date();
const startOfDay = new Date(
  now.getFullYear(),
  now.getMonth(),
  now.getDate() - 30,
  0,
  0
);
const endOfDay = new Date(
  now.getFullYear(),
  now.getMonth(),
  now.getDate(),
  23,
  59
);
const dateRangeStart = ref(
  startOfDay.toISOString().slice(0, 16).replace("T", " ")
);

const dateRangeEnd = ref(endOfDay.toISOString().slice(0, 16).replace("T", " "));

const isFatal = ref<number | "">("");
const isInjured = ref<number | "">("");
const hasIsolation = ref<number | "">("");
const cause = ref("");
const form = ref("");

const isShow = ref(false);
const isFatalChange = ref(false);
const isInjuredChange = ref(false);
const isGeLiSheshi = ref(false);
const isGeneralOptions = ref(false);
const isGeneralOptions1 = ref(false);

const fatalOptions = [
  { value: 0, label: "否" },
  { value: 1, label: "是" },
];

const injuredOptions = [
  { value: 0, label: "否" },
  { value: 1, label: "是" },
];

const isolationOptions = [
  { value: 0, label: "否" },
  { value: 1, label: "是" },
];

const isFatalLabel = ref("");
const isInjuredLabel = ref("");
const hasIsolationLabel = ref("");
const selectedCause = ref("");
const selectedForm = ref("");

const selectFatalOption = (item: { value: number; label: string }) => {
  isFatal.value = item.value;
  isFatalLabel.value = item.label;
  isFatalChange.value = false;
};

const selectInjuredOption = (item: { value: number; label: string }) => {
  isInjured.value = item.value;
  isInjuredLabel.value = item.label;
  isInjuredChange.value = false;
};

const selectIsolationOption = (item: { value: number; label: string }) => {
  hasIsolation.value = item.value;
  hasIsolationLabel.value = item.label;
  isGeLiSheshi.value = false;
};

const selectCause = (causes: { id: number; value: string }) => {
  selectedCause.value = causes.value;
  cause.value = causes.value;
  isGeneralOptions.value = false;
};

const selectForm = (pattern: { id: number; value: string }) => {
  selectedForm.value = pattern.value;
  form.value = pattern.value;
  isGeneralOptions1.value = false;
};

// 新增：控制抽屉显示和隐藏的变量
const drawerVisible = ref(false);

// 新增：页面加载时调用接口获取事故原因和事故形式的数据
const accidentCauses = ref<any[]>([]);
const accidentPatterns = ref<any[]>([]);
const responseData = ref<any>(null);

onMounted(async () => {
  try {
    // 调用接口获取事故原因数据
    const reasonResponse = await GetAccidentCause();
    accidentCauses.value = Array.isArray(reasonResponse)
      ? reasonResponse.map((cause: any) => ({
          id: cause.id,
          value: cause.value,
        }))
      : [];
  } catch (error) {
    // 捕获并处理错误
    console.error("获取事故原因数据失败：", error);
    accidentCauses.value = [];
  }
  try {
    const formResponse = await GetAccidentPattern();
    accidentPatterns.value = Array.isArray(formResponse)
      ? formResponse.map((pattern: any) => ({
          id: pattern.id,
          value: pattern.value,
        }))
      : [];
  } catch (error) {
    // 捕获并处理错误
    console.error("获取事故形式数据失败：", error);
    accidentPatterns.value = [];
  }
});

// 新增：定义 fetchData 方法
const fetchData = async () => {
  try {
    const formatDateTime = (dateTime: string) => {
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    };
    dateRangeStart.value = formatDateTime(dateRangeStart.value);
    dateRangeEnd.value = formatDateTime(dateRangeEnd.value);
    const params: any = {
      startTime: dateRangeStart.value
        ? formatDateTime(dateRangeStart.value)
        : "",
      endTime: dateRangeEnd.value ? formatDateTime(dateRangeEnd.value) : "",
      deathFlag: isFatal.value,
      hurtFlag: isInjured.value,
      glssFlag: hasIsolation.value,
      reason: cause.value,
      sgxt: form.value,
    };
    const accidentResponse = await GetAccident(params);
    responseData.value = accidentResponse;
    selectedParams.value = params;
  } catch (error) {
    console.error("调用接口失败：", error);
  }
};

// 新增：定义 selectedParams 对象
const selectedParams = ref<any>({});

// 监听 type 属性变化，清除筛选条件
watch(
  () => props.type,
  () => {
    isFatal.value = "";
    isInjured.value = "";
    hasIsolation.value = "";
    cause.value = "";
    form.value = "";
    isFatalLabel.value = "";
    isInjuredLabel.value = "";
    hasIsolationLabel.value = "";
    selectedCause.value = "";
    selectedForm.value = "";
    isFatalChange.value = false;
    isInjuredChange.value = false;
    isGeLiSheshi.value = false;
    isGeneralOptions.value = false;
    isGeneralOptions1.value = false;

    // 重置日期范围
    const startOfDay = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate() - 30,
      0,
      0
    );
    const endOfDay = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate(),
      23,
      59
    );
    dateRangeStart.value = startOfDay
      .toISOString()
      .slice(0, 16)
      .replace("T", " ");
    dateRangeEnd.value = endOfDay.toISOString().slice(0, 16).replace("T", " ");

    fetchData();
  }
);

watch([dateRangeStart, dateRangeEnd], () => {
  fetchData();
});
// 新增：监听 isShow 的变化
watch(isShow, (newValue) => {
  if (!newValue) {
    isFatalChange.value = false;
    isInjuredChange.value = false;
    isGeLiSheshi.value = false;
    isGeneralOptions.value = false;
    isGeneralOptions1.value = false;
  }
});

// 新增：定义 showDateTimePicker 方法
const showDateTimePicker = (event: Event) => {
  (event.target as HTMLInputElement).showPicker();
};

defineExpose({
  selectedParams,
});
</script>
  <style lang="less" scoped>
.dropdown-menuMax {
  position: fixed;
  top: 10%;
  width: 100vw;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-items: center;
  color: white;
  font-size: 14px;
  .dropdown-menu {
    display: flex;
    position: fixed;
    top: 100px;
    border: none;
    border-radius: 8px;
    padding: 10px;
    background: rgba(0, 0, 0, 0.7);
    gap: 30px;
    .button {
      background: none;
      border: none;
      color: white;
    }
  }
  .scustom-select-content {
    position: relative;
    top: 60px;
    width: 450px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    border-radius: 20px;
    background: rgba(0, 0, 0, 0.7);
  }

  .selectShow {
    min-width: 100px;
    margin: 10px 0; // 增加间距
    position: relative; // 修改为相对定位
    padding: 10px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .time {
      gap: 10px; // 增加间距
    }
    .span {
      line-height: 10px;
      margin-right: 5px;
    }
    .custom-select {
      position: relative;
      min-width: 80px;
      cursor: pointer;
      padding: 5px;
      border-radius: 8px;
      text-align: center;
      font-size: 14px; // 增加字体大小
      color: gray;
      border: 1px solid rgba(0, 0, 0, 0.7);
    }

    .custom-options {
      min-width: 100px;
      position: absolute;
      top: 100%;
      border: 1px solid rgba(0, 0, 0, 0.7);
      border-radius: 8px;
      z-index: 1000;
      text-align: center;
      background: rgba(0, 0, 0, 0.7);
      color: white;

      .custom-option {
        padding: 10px;
        cursor: pointer;
        min-width: 150px;
        font-size: 14px; // 增加字体大小
      }
      .custom-option:hover {
        background-color: #36639f; // 鼠标悬停时的背景色
      }
    }
    .inputtiem {
      border: 1px solid rgba(0, 0, 0, 0.7);
      border-radius: 8px;
      overflow: hidden;
    }
    input[type="datetime-local"] {
      min-width: 40%;
      padding: 10px;
      border: none; // 边框颜色
      font-size: 14px; // 增加字体大小
      background: rgba(0, 0, 0, 0.4);
      color: white;
    }
  }
}
</style>
  